package ru.ifmo.network.skype.view.swing;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

import static ru.ifmo.network.SwingUtils.getBox;
import static ru.ifmo.network.SwingUtils.invokeLaterIfNotEDT;


/**
 * @author avhaliullin
 */
public class ActiveItemsList<T> extends JPanel {
    private final ComponentProvider<T> provider;
    private final Map<T, JComponent> componentMap = new HashMap<T, JComponent>();
    private final JComponent pane;
    private final JScrollPane scrollPane;

    public ActiveItemsList(ComponentProvider<T> provider) {
        this.provider = provider;
        pane = getBox(true);
        scrollPane = new JScrollPane(pane);
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        scrollPane.createVerticalScrollBar();
        add(scrollPane);
    }

    public void add(final T item) {
        if (!componentMap.containsKey(item)) {
            invokeLaterIfNotEDT(new Runnable() {
                @Override
                public void run() {
                    JComponent component = provider.getComponent(item);
                    componentMap.put(item, component);
                    pane.add(component);
                    pane.repaint();
                    scrollPane.revalidate();
                }
            });
        }
    }

    public void remove(final T item) {
        invokeLaterIfNotEDT(new Runnable() {
            @Override
            public void run() {
                JComponent component = componentMap.remove(item);
                if (component != null) {
                    component.setVisible(false);
                    pane.remove(component);
                }
            }
        });
    }
}
